package com.powernode.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.powernode.domain.Prod;
import com.powernode.domain.UserCollection;
import com.powernode.service.UserCollectionService;
import com.powernode.utils.PowerAuthMenuUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/p/collection")
@Api(tags = "小程序收藏接口")
public class CollectionController {

    @Autowired
    private UserCollectionService userCollectionService;


    @GetMapping("/count")
    @ApiOperation(value = "收藏数量")
    public ResponseEntity<Integer> getRoleList() {
        //获取当前用户id  通过上下文
        String wxUserId = PowerAuthMenuUtil.getWxUserId();
        int count = userCollectionService.count(new LambdaQueryWrapper<UserCollection>()
                .eq(!ObjectUtils.isEmpty(wxUserId), UserCollection::getUserId, wxUserId));
        return ResponseEntity.ok(count);
    }

    @GetMapping("/prods")
    @ApiOperation(value = "收藏")
    public ResponseEntity<Page<Prod>> getProdList(Page<Prod> page) {
        //获取当前用户id  通过上下文
        String wxUserId = PowerAuthMenuUtil.getWxUserId();
        page = userCollectionService.getProdList(page, wxUserId);
        return ResponseEntity.ok(page);
    }

    @GetMapping("/isCollection")
    @ApiOperation(value = "商品是否收藏")
    public ResponseEntity<Boolean> getProdIsCollection(Long prodId) {
        //获取当前用户id  通过上下文
        String wxUserId = PowerAuthMenuUtil.getWxUserId();
        //得到该用户的对应该商品id的个数 如果大于0 表示收藏了
        int count = userCollectionService.count(new LambdaQueryWrapper<UserCollection>()
                .eq(UserCollection::getProdId, prodId)
                .eq(UserCollection::getUserId, wxUserId));
        return ResponseEntity.ok(count > 0);
    }

    @PostMapping("/addOrCancel")
    @ApiOperation(value = "商品收藏点击")
    public ResponseEntity<Void> prodAddOrCancel(@RequestBody Long prodId) {
        //获取当前用户id  通过上下文
        String wxUserId = PowerAuthMenuUtil.getWxUserId();
        userCollectionService.prodAddOrCancel(wxUserId, prodId);
        return ResponseEntity.ok().build();
    }


}
